package com.goldgov.conference.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.gtiles.components.securityworkbench.bean.SwbAuthUser;
import org.gtiles.core.module.auditlog.bean.AuditLogBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.auditlog.service.AuditLog;
import com.goldgov.auditlog.service.IAuditLogService;
import com.goldgov.authorityInfo.service.AuthorityInfoInit;
import com.goldgov.conference.service.Conference;
import com.goldgov.conference.service.ConferenceAttendance;
import com.goldgov.conference.service.ConferenceAttendanceService;
import com.goldgov.conference.service.ConferenceBean;
import com.goldgov.conference.service.ConferenceQuery;
import com.goldgov.conference.service.ConferenceService;
import com.goldgov.conference.service.ConferenceStat;
import com.goldgov.conference.service.ConferenceStatQuery;
import com.goldgov.conference.service.ConferenceStatService;
import com.goldgov.conference.service.ConferenceUser;
import com.goldgov.conference.service.ConferenceUserQuery;
import com.goldgov.conference.service.ConferenceUserService;
import com.goldgov.distancelearning.service.Distancelearning;
import com.goldgov.distancelearning.service.DistancelearningQuery;
import com.goldgov.distancelearning.service.DistancelearningService;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.notice.service.NoticeQuery;
import com.goldgov.notice.service.NoticeService;
import com.goldgov.notifyrecord.service.NotifyRecordService;
import com.goldgov.securityworkbench.attachment.AttachementBean;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.DateUtil;
import com.goldgov.utils.IpUtil;
import com.goldgov.utils.JsonUtil;
import com.goldgov.utils.PrintUtil;
import com.goldgov.utils.PropertyUtil;
import com.goldgov.utils.UrlUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/** 
 * @ClassName: ConferenceController 
 * @Description: TODO
 * @author hanxiangyu
 * @date 2018年6月4日 上午10:25:22 
 */

@RestController
@RequestMapping("/workbench/conference")
@Api("三会一课服务接口")
public class ConferenceController {
	
	@Autowired
	private ConferenceService conferenceService;
	
	//回执/会议记录与用户关系 服务接口
	@Autowired
	private ConferenceUserService conferenceUserService;
	
	//考勤记录服务接口
	@Autowired
	private ConferenceAttendanceService conferenceAttendanceService;
	//发送通知接口
	@Autowired
	private NotifyRecordService notifyRecordService;
	
	@Autowired
	private RemoteCallService remoteCallService;
	
	@Autowired
	private ConferenceStatService conferenceStatService;
	@Autowired
	private DistancelearningService distancelearningService;
	
	@Autowired
	private NoticeService noticeService;
	
	@Autowired
	private IAuditLogService auditLogService;
	
	/**
	 * 预新增
	 * @param obj
	 * @param request
	 * @return
	 */
	@GetMapping("/preAddConference")
	@ApiOperation(value = "预新增会议", notes ="查询返回会议ID")
	public JsonSuccessObject<Conference> preAddConference(Conference obj,HttpServletRequest request){
		obj = conferenceService.getConferenceID();
		JsonSuccessObject<Conference> returnResult = new JsonSuccessObject<Conference>(obj);
		return returnResult;
	}
	
	
	@PostMapping("/addAndUpdateConferenceUser")
	@ApiOperation(value = "新增更新会议关联用户", notes = "新增会议用户记录" )
	public JsonObject<Object> addConferenceUser(ConferenceUser obj,HttpServletRequest request,HttpServletResponse response)throws Exception{
		List<ConferenceUser> existUserIDs = conferenceService.getExistUserIDs(obj.getUserIDs(), obj.getConferenceID());
		if (!existUserIDs.isEmpty()) {
			String[] conferenceUserIDs = new String[existUserIDs.size()];
			String[] userIDs = new String[existUserIDs.size()];
			for (int i = 0; i < existUserIDs.size(); i++) {
				conferenceUserIDs[i] = existUserIDs.get(i).getConferenceUserID();
				userIDs[i] = existUserIDs.get(i).getUserID();
			}
			List<String> userIDslist = new ArrayList(Arrays.asList(userIDs));
			List<String> idslist = new ArrayList(Arrays.asList(obj.getUserIDs()));
			idslist.removeAll(userIDslist);
			String[] addUserIDs = new String[idslist.size()]; 
			idslist.toArray(addUserIDs);//list-->数组
			
			if(null!=conferenceUserIDs && conferenceUserIDs.length>0) {
				conferenceService.deleteConferenceCorrelation(obj.getConferenceID(),conferenceUserIDs);
			}
			
			ConferenceUser conferenceUser = new ConferenceUser();
			conferenceUser.setPeopleNum(existUserIDs.size() + idslist.size());
			conferenceUser.setUserIDs(addUserIDs);
			conferenceUser.setConferenceID(obj.getConferenceID());
			//远程教育的
			Conference conference = conferenceService.getConferenceById(obj.getConferenceID());
			if(conference.getConferenceType().contains("5")) {
				conference.setUserIDs(addUserIDs);
				addOrUpdateDistancelearning(conference,2, request, response);
			}
			conferenceService.addConferenceUser2(conferenceUser);
			if ("1".equals(conference.getIsSend()) && conference.getPublishState().intValue() == ConferenceQuery.PUBLISHSTATE_YES) {
				SwbAuthUser u = LoginAuthUser.getUserByAdmin(request);
				if (obj.getUserIDs().length > 0) {
					conference.setUserIDs(obj.getUserIDs());
					conference.setUserID(u.getEntityID());
					conference.setUserName(u.getName());
					noticeService.sendNotice(conference,NoticeQuery.NOTICE_ADD);
				}
			}
		}else {
//			ConferenceUser conferenceUser = new ConferenceUser();
			obj.setPeopleNum(obj.getUserIDs().length);
//			conferenceUser.setUserIDs(obj.getUserIDs());
//			conferenceUser.setConferenceID(obj.getConferenceID());
			conferenceService.addConferenceUser2(obj);
			Conference conference = conferenceService.getConferenceById(obj.getConferenceID());
			//包含远程会议的添加到远程会议
			if(conference.getConferenceType().contains("5")) {
				conference.setUserIDs(obj.getUserIDs());
				addOrUpdateDistancelearning(conference,1, request, response);
			}
			if ("1".equals(conference.getIsSend()) && conference.getPublishState().intValue() == ConferenceQuery.PUBLISHSTATE_YES) {
					SwbAuthUser u = LoginAuthUser.getUserByAdmin(request);
					if (obj.getUserIDs().length > 0) {
						conference.setUserIDs(obj.getUserIDs());
						conference.setUserID(u.getEntityID());
						conference.setUserName(u.getName());
						noticeService.sendNotice(conference,NoticeQuery.NOTICE_ADD);
				}
			}
		}
		return JsonSuccessObject.SUCCESS;
	}
	
	
	
	/**
	 * 
	 * @date 2018年6月6日 下午4:43:35 
	 * @author hanxiangyu
	 * @param obj
	 * @param request
	 * @param ids 出席人userID
	 * @param conferenceTypes 三会一课类型
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("/addConferenceByAdmin")
	@ApiOperation(value = "新增会议后台", notes = "新增会议记录管理端" )
	public JsonObject<Object> addConferenceByAdmin(Conference obj,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SwbAuthUser u = LoginAuthUser.getUserByAdmin(request);
		obj.setUserID(u.getEntityID());//发布人id
		obj.setUserName(u.getName());//发布人姓名
//		String[] userids = {u.getEntityID()};
//		obj.setUserIDs(userids);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if(null!=obj.getConferenceBeginDate() && !"".equals(obj.getConferenceBeginDate())) {
				Date conferenceBeginTime=sdf.parse(obj.getConferenceBeginDate());
				//设置当前年份
				String year = String.valueOf(DateUtil.getYear(conferenceBeginTime));
				obj.setYear(year);
				//设置季度
				obj.setQuarter(DateUtil.getSeason(conferenceBeginTime));
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (obj.getOrganizationId() == null || "".equals(obj.getOrganizationId())) {
			obj.setOrganizationId(conferenceService.getOrgIdByUserId(u.getEntityID()));
		}
		if(obj.getLastModifiedDate()==null||obj.getLastModifiedDate().equals("")) {
			//最后修改时间
			obj.setLastModifiedDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		}
		if(obj.getCreateDate()==null||obj.getCreateDate().equals("")) {
			//创建时间
			obj.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		}
		//发布时间
//		obj.setPublishDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		//默认不发布
		obj.setPublishState(ConferenceQuery.PUBLISHSTATE_NO);
		obj.setActiveState(ConferenceQuery.ACTIVESTATE_YES);
		conferenceService.addConference(obj);
//		ConferenceUser conferenceUser = new ConferenceUser();
//		conferenceUser.setUserIDs(userids);
//		conferenceUser.setConferenceID(obj.getConferenceID());
//		conferenceService.addConferenceUser2(conferenceUser);
		//判断是否需要发送通知 1需要 2不需要
//		if (obj.getIsSend() != null && Integer.parseInt(obj.getIsSend()) == 1) {
//			if (obj.getUserIDs().length > 0) {
//				obj.setUserIDs(userids);
//				notifyRecordService.addConNotifyRecord(obj);
//			}
//		}
		//添加远程教育记录
		if(obj.getConferenceType().contains("5")) {
			this.addOrUpdateDistancelearning(obj, 1, request, response);
		}
		/*添加记录日志*/
		String operateContent = "conferenceID="+obj.getConferenceID()+",isSend="+obj.getIsSend()+",conferenceSite="+obj.getConferenceSite()
		+ ",compere="+obj.getCompere()+",conferenceName="+obj.getConferenceName()+",conferencePresentation="+obj.getConferencePresentation()
				+ ",conferenceBeginDate="+obj.getConferenceBeginDate()+",conferenceEndDate="+obj.getConferenceEndDate()
						+ ",conferenceType="+obj.getConferenceType()+",conferenceTypes="+Arrays.toString(obj.getConferenceTypes()==null?new String[]{}:obj.getConferenceTypes());
		AuditLog auditLog = new AuditLog();
		auditLog.setOperateType("Save");
		auditLog.setModuleName("三会一课"); 
		auditLog.setOperateName("新增");
		auditLog.setOperateTime(new Date());
		auditLog.setOperateUserId(u.getSwbUserId());
		auditLog.setOperateUserName(u.getUserName());
		auditLog.setOperateState(AuditLogBean.OPERATE_STATE_SUCCESS);
		auditLog.setOperateIp(IpUtil.getIpAddress(request));
		auditLog.setOperateUrl(request.getRequestURL().toString());
		auditLog.setOperateContent(operateContent);
		auditLogService.addAuditLog(auditLog);
		return JsonSuccessObject.SUCCESS; 
	}
	
	@RequestMapping("/listConferenceByAdmin")
	@ApiOperation(value = "管理员查询多条会议", notes ="三会一课列表管理员")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchConferenceType", value = "会议类型", paramType = "query"),
		 @ApiImplicitParam(name = "searchConferenceBeginDate", value = "会议开始时间", paramType = "query"),
		 @ApiImplicitParam(name = "searchIshave", value = "是否存在附件", paramType = "query"),
		 @ApiImplicitParam(name = "searchConferenceName", value = "会议名称", paramType = "query"),
		 @ApiImplicitParam(name = "searchMeetingStatus", value = "会议状态", paramType = "query"),
		 @ApiImplicitParam(name = "searchOrganizationId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchChilderOrg", value = "是否包含子部门", paramType = "query"),
		 @ApiImplicitParam(name = "queryOrganizationName", value = "机构名称", paramType = "query"),
		 @ApiImplicitParam(name = "searchConferenceEndDate", value = "会议结束时间", paramType = "query")})
	public JsonQueryObject<Conference> getConferenceListByAdmin(@ApiIgnore ConferenceQuery query,HttpServletRequest request,Model model){
		List<Conference> list = new ArrayList<>();
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.shyk,request);
		if (query.getSearchYear() == null || "".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		if (query.getSearchOrganizationId() != null && "-1".equals(query.getSearchOrganizationId())) {
			query.setSearchScopeCode(u);
			list = conferenceService.getConferenceListByAdmin(query);
		}else if (query.getSearchOrganizationId() == null || "".equals(query.getSearchOrganizationId())) {
			query.setSearchScopeCode(u);
		}else {
			query.setSearchScopeCode(u);
			list = conferenceService.getConferenceListByAdmin(query);
		}
		 
//		SwbAuthUser user = LoginAuthUser.getUserByAdmin(request);
//		query.setSearchUserId(user.getEntityID());
		if(null!=list && list.size()>0) {
			for(Conference c:list) {
			    Map params=new HashMap();
				params.put("groupId", c.getConferenceID());
				String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
				JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
				JSONArray jsonList=json.getJSONArray("resultList");
				List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
				for(AttachementBean att:ab) {
					att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
					if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
						att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
					}else {
						att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
					}
				}
				c.setFileList(ab);
			}
		}
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	
	@GetMapping
	@ApiOperation(value = "查询多条会议", notes ="三会一课列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchConferenceType", value = "会议类型", paramType = "query"),
	 @ApiImplicitParam(name = "searchConferenceBeginDate", value = "会议开始时间", paramType = "query"),
	 @ApiImplicitParam(name = "searchConferenceName", value = "会议名称", paramType = "query"),
	 @ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
	 @ApiImplicitParam(name = "searchQuarter", value = "季度", paramType = "query"),
	 @ApiImplicitParam(name = "searchMeetingStatus", value = "会议状态", paramType = "query"),
	 @ApiImplicitParam(name = "searchUserId", value = "当前登录用户测试使用", paramType = "query"),
	 @ApiImplicitParam(name = "searchConferenceEndDate", value = "会议结束时间", paramType = "query")})
	public JsonQueryObject<Conference> getConferenceList(@ApiIgnore ConferenceQuery query,HttpServletRequest request,Model model){
//		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
//		query.setSearchScopeCode(u);
		//当前登录的用户
		SwbAuthUser loginu = LoginAuthUser.getUserByAdmin(request);
		if (query.getSearchUserId() == null || "".equals(query.getSearchUserId())) {
			query.setSearchUserId(loginu.getEntityID());
		}
		List<Conference> list = conferenceService.getConferenceList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
//	@PutMapping
//	@ApiOperation(value = "更新会议记录", notes ="三会一课更新")
//	public JsonObject<Object> updateConference(Conference obj,HttpServletRequest request,@ApiParam(value = "userIDs", required = true) @RequestParam("ids") String[] ids){
//		List<ConferenceUser> conferenceUser = new ArrayList<>();
//		//查询已存在的数据
//		List<ConferenceUser> existUserIDs = conferenceService.getExistUserIDs(ids, obj.getConferenceID());
//		String[] conferenceUserIDs = new String[existUserIDs.size()];
//		String[] userIDs = new String[existUserIDs.size()];
//		for (int i = 0; i < existUserIDs.size(); i++) {
//			conferenceUserIDs[i] = existUserIDs.get(i).getConferenceUserID();
//			userIDs[i] = existUserIDs.get(i).getUserID();
//		}
//		List<String> userIDslist = new ArrayList(Arrays.asList(userIDs));
//		List<String> idslist = new ArrayList(Arrays.asList(ids));
//		idslist.removeAll(userIDslist);
//		for (String id : idslist) {
//			ConferenceUser cu = new ConferenceUser();
//			cu.setUserID(id);
//			cu.setConferenceID(obj.getConferenceID());
//			cu.setConferenceUserID(conferenceService.getConferenceID().getConferenceID());
//			conferenceUser.add(cu);
//		}
//		if(obj.getLastModifiedDate()==null||obj.getLastModifiedDate().equals("")) {
//			//最后修改时间
//			obj.setLastModifiedDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//		}
//		
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		try {
//			if(null!=obj.getConferenceBeginDate() && !"".equals(obj.getConferenceBeginDate())) {
//				Date conferenceBeginTime=sdf.parse(obj.getConferenceBeginDate());
//				//设置当前年份
//		        String year = String.valueOf(DateUtil.getYear(conferenceBeginTime));
//		        obj.setYear(year);
//				//设置季度
//				obj.setQuarter(DateUtil.getSeason(conferenceBeginTime));
//			}
//			
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//		
//		conferenceService.updateConference(obj);//修改
//		if(null!=conferenceUserIDs && conferenceUserIDs.length>0) {
//			conferenceService.deleteConferenceCorrelation(obj.getConferenceID(),conferenceUserIDs);
//		}
//		if(null!=conferenceUser && conferenceUser.size()>0) {
//			conferenceService.addConferenceUser(conferenceUser);
//		}
//		return JsonSuccessObject.SUCCESS;
//	}
	@PutMapping("/updateConference")
	@ApiOperation(value = "更新会议记录", notes ="三会一课更新")
	public JsonObject<Object> updateConferenceBy(Conference obj,HttpServletRequest request,Model model,HttpServletResponse response){
		SwbAuthUser u = LoginAuthUser.getUserByAdmin(request);
		if(obj.getLastModifiedDate()==null||obj.getLastModifiedDate().equals("")) {
			//最后修改时间
			obj.setLastModifiedDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if(null!=obj.getConferenceBeginDate() && !"".equals(obj.getConferenceBeginDate())) {
				Date conferenceBeginTime=sdf.parse(obj.getConferenceBeginDate());
				//设置当前年份
				String year = String.valueOf(DateUtil.getYear(conferenceBeginTime));
				obj.setYear(year);
				//设置季度
				obj.setQuarter(DateUtil.getSeason(conferenceBeginTime));
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		try {
			conferenceService.updateConference(obj);//修改
			//修改远程教育
			Conference c=conferenceService.getConferenceById(obj.getConferenceID());
			if(c.getConferenceType().contains("5")) {
				addOrUpdateDistancelearning(c, 2, request, response);
			}
			/*添加记录日志*/
			String operateContent = "conferenceID="+obj.getConferenceID()+",isSend="+obj.getIsSend()+",conferenceSite="+obj.getConferenceSite()
			+ ",compere="+obj.getCompere()+",conferenceName="+obj.getConferenceName()+",conferencePresentation="+obj.getConferencePresentation()
					+ ",conferenceBeginDate="+obj.getConferenceBeginDate()+",conferenceEndDate="+obj.getConferenceEndDate()
							+ ",conferenceType="+obj.getConferenceType()+",conferenceTypes="+Arrays.toString(obj.getConferenceTypes()==null?new String[]{}:obj.getConferenceTypes());
			AuditLog auditLog = new AuditLog();
			auditLog.setOperateType("Update");
			auditLog.setModuleName("三会一课");
			auditLog.setOperateName("更新");
			auditLog.setOperateTime(new Date());
			auditLog.setOperateUserId(u.getSwbUserId());
			auditLog.setOperateUserName(u.getUserName());
			auditLog.setOperateState(AuditLogBean.OPERATE_STATE_SUCCESS);
			auditLog.setOperateIp(IpUtil.getIpAddress(request));
			auditLog.setOperateUrl(request.getRequestURL().toString());
			auditLog.setOperateContent(operateContent);
			auditLogService.addAuditLog(auditLog);
			return JsonUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.error();
		}
	}
	
	@DeleteMapping
	@ApiOperation(value = "取消会议", notes ="取消三会一课")
	public JsonObject<Object> cancelConference(@ApiParam(value = "conferenceIDs", required = true) @RequestParam("ids") String[] ids,HttpServletRequest request){
		SwbAuthUser u = LoginAuthUser.getUserByAdmin(request);
		conferenceService.cancelConference(ids, ConferenceQuery.ACTIVESTATE_NO);
		/*添加记录日志*/
		AuditLog auditLog = new AuditLog();
		auditLog.setOperateType("None");
		auditLog.setModuleName("三会一课");
		auditLog.setOperateName("取消");
		auditLog.setOperateTime(new Date());
		auditLog.setOperateUserId(u.getSwbUserId());
		auditLog.setOperateUserName(u.getUserName());
		auditLog.setOperateState(AuditLogBean.OPERATE_STATE_SUCCESS);
		auditLog.setOperateIp(IpUtil.getIpAddress(request));
		auditLog.setOperateUrl(request.getRequestURL().toString());
		auditLog.setOperateContent("取消三会一课:"+Arrays.toString(ids));
		auditLogService.addAuditLog(auditLog);
		return new JsonSuccessObject<Object>(null, "2000", "取消成功"); 
	}
	
	@PutMapping("/updateReceipt")
	@ApiOperation(value = "回执操作/请假", notes ="对三会一课的回执/请假操作")
	public JsonObject<Object> updateReceipt(ConferenceUser obj,HttpServletRequest request){
		//回执时间
		obj.setReceiptDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		conferenceUserService.updateReceipt(obj);
		ConferenceUser cu = conferenceUserService.getConferenceUser(obj);
		if (null != obj.getReceiptType() && obj.getReceiptType() == 3) {
			Conference conference = new Conference();
			conference.setConferenceID(obj.getConferenceID());
			conference.setQjNum(1);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			conference.setLastModifiedDate(sdf.format(new Date()));
			conferenceService.updateConference(conference);
			//通过关系表id确定是否存在考勤记录
			List<ConferenceAttendance> attendanceList = conferenceAttendanceService.getConferenceAttendanceList(cu.getConferenceUserID());
			if (!attendanceList.isEmpty()) {
				Conference c = new Conference();
				c.setConferenceID(obj.getConferenceID());
				c.setYqNum(1);
				conferenceService.updateNum(c);
				conferenceAttendanceService.deleteConferenceAttendance(cu.getConferenceUserID());
			}
		}
		return JsonSuccessObject.SUCCESS;
	}
	@PostMapping("/addAttendance")
	@ApiOperation(value = "考勤记录", notes ="对三会一课的考勤记录")
	public JsonObject<Object> addAttendance(ConferenceAttendance obj,HttpServletRequest request){
		obj.setAttendanceDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		if (obj.getAttendanceStatus() == null) {
			obj.setAttendanceStatus(ConferenceQuery.STATUS_YQ);
		}
		//获取用户与记录的关系表 存入考勤表中
		ConferenceUser conferenceUser = new ConferenceUser();
		conferenceUser.setConferenceID(obj.getConferenceID());
		conferenceUser.setUserID(obj.getUserID());
		ConferenceUser cu = conferenceUserService.getConferenceUser(conferenceUser);
		//签到时更新一下回执表,以防存在请假
		if (cu.getReceiptType() != null && cu.getReceiptType() == 3) {
			conferenceUser.setReceiptType(ConferenceQuery.STATUS_YQ);
			conferenceUserService.updateReceipt(conferenceUser);
			Conference c = new Conference();
			c.setConferenceID(obj.getConferenceID());
			c.setQjNum(1);
			conferenceService.updateNum(c);
		}
		//通过关系表id确定是否存在考勤记录
		List<ConferenceAttendance> attendanceList = conferenceAttendanceService.getConferenceAttendanceList(cu.getConferenceUserID());
		//只存在一条考勤记录时
		if (attendanceList.isEmpty()) {//判断是否有考勤记录如不存在考勤记录更新会议表考勤数+1
			Conference conference = new Conference();
			conference.setConferenceID(obj.getConferenceID());
			conference.setYqNum(1);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			conference.setLastModifiedDate(sdf.format(new Date()));
			conferenceService.updateConference(conference);
			obj.setConferenceUserID(cu.getConferenceUserID());
			conferenceAttendanceService.addConferenceAttendance(obj);
		}else {
			obj.setConferenceUserID(cu.getConferenceUserID());
			conferenceAttendanceService.updateConferenceAttendance(obj);
		}
		
		
		//存在多条考勤记录时
//       if (attendanceList.isEmpty()) {//判断是否有考勤记录如不存在考勤记录更新会议表考勤数+1
//			Conference conference = new Conference();
//			conference.setConferenceID(obj.getConferenceID());
//			conference.setYqNum(1);
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			conference.setLastModifiedDate(sdf.format(new Date()));
//			conferenceService.updateConference(conference);
//			
//		}
//       	obj.setConferenceUserID(conferenceUserID);
//		conferenceAttendanceService.addConferenceAttendance(obj);
		return JsonSuccessObject.SUCCESS;
	}
	
	
	
	@GetMapping("/{id}")
	@ApiOperation(value = "根据主键查询会议记录", notes ="会议详情")
	public JsonSuccessObject<Conference> getConference(@ApiParam(value="conferenceID",required=false) @PathVariable("id") String id,HttpServletRequest request){
		Conference obj = new Conference();
		obj.setConferenceID(id);
		SwbAuthUser u = LoginAuthUser.getUserByAdmin(request);
		obj.setUserID(u.getEntityID());
		Conference conference = conferenceService.getConference(obj);
		
		//获取请假人员列表
		List<ConferenceUser> qjList=conferenceUserService.getConferenceUserQjList(conference.getConferenceID());
		conference.setQjList(qjList);
		//获取缺席人员列表
		List<ConferenceUser> qxList=conferenceUserService.getConferenceUserQxList(conference.getConferenceID());
		conference.setQxList(qxList);
		//获取考勤人员列表
		List<ConferenceUser> qdList = conferenceUserService.getConferenceUserQdList(conference.getConferenceID());
		if (!qdList.isEmpty()) {
			conference.setQdList(qdList);
		}
		//获取出席人列表
		List<ConferenceUser> cxList = conferenceUserService.getConferenceUserCxList(conference.getConferenceID());
		conference.setConferenceUserList(cxList);
		JsonSuccessObject<Conference> returnResult = new JsonSuccessObject<>(conference);
		return returnResult;
	}
	
	@PostMapping("/publishConference")
	@ApiOperation(value = "会议发布撤销操作", notes ="会议发布撤销操作")
	public JsonObject<Object> publishConference(Conference obj,HttpServletRequest request,HttpServletResponse response){
		SwbAuthUser u = LoginAuthUser.getUserByAdmin(request);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Conference con = conferenceService.getConferenceById(obj.getConferenceID());
		if (obj.getPublishState().intValue() == 1) {
			obj.setPublishDate(sdf.format(new Date()));
			//发送通知
			con.setPublishState(ConferenceQuery.PUBLISHSTATE_NO);
			if (con.getIsSend() != null && "1".equals(con.getIsSend())) {
				ConferenceUser cu = new ConferenceUser();
				cu.setConferenceID(con.getConferenceID());
				List<String> userIds = conferenceUserService.getConferenceUserIds(cu);
				if (!userIds.isEmpty()) {
					String[] userIDs = new String[userIds.size()]; 
					userIds.toArray(userIDs);//list-->数组
					con.setUserIDs(userIDs);
					if (con.getConferenceType().equals("5")) {
						Distancelearning d=distancelearningService.getDisByID(obj.getConferenceID());
						d.setPublishState(ConferenceQuery.PUBLISHSTATE_YES);
						d.setPublishDate(new Date());
						distancelearningService.publishDistancelearning(d);
						if(!noticeService.sendDisNotice(d,NoticeQuery.NOTICE_ADD)) {
							PrintUtil.printMsg(response, false,"会议时发送通知失败!");
						}
					} else {
						if(!noticeService.sendNotice(con,NoticeQuery.NOTICE_ADD)) {
							PrintUtil.printMsg(response, false,"发布会议时发送通知失败!");
						}
					}
				}
			}
		}else {
			//发送通知
			con.setPublishState(ConferenceQuery.PUBLISHSTATE_YES);
			if (con.getIsSend() != null && "1".equals(con.getIsSend())) {
				ConferenceUser cu = new ConferenceUser();
				cu.setConferenceID(con.getConferenceID());
				List<String> userIds = conferenceUserService.getConferenceUserIds(cu);
				if (!userIds.isEmpty()) {
					String[] userIDs = new String[userIds.size()]; 
					userIds.toArray(userIDs);//list-->数组
					con.setUserIDs(userIDs);
					if (con.getConferenceType().equals("5")) {
						Distancelearning d=distancelearningService.getDisByID(obj.getConferenceID());
						d.setPublishState(ConferenceQuery.PUBLISHSTATE_YES);
						d.setPublishDate(new Date());
						distancelearningService.publishDistancelearning(d);
						if(!noticeService.sendDisNotice(d,NoticeQuery.NOTICE_CANCEL)) {
							PrintUtil.printMsg(response, false,"撤销会议时发送通知失败!");
						}
					} else {
						if(!noticeService.sendNotice(con,NoticeQuery.NOTICE_CANCEL)) {
							PrintUtil.printMsg(response, false,"撤销会议时发送通知失败!");
						}
					}
				}
			}
		}
		/*添加记录日志*/
		AuditLog auditLog = new AuditLog();
		auditLog.setOperateType("None");
		auditLog.setModuleName("三会一课");
		auditLog.setOperateName("发布/取消发布");
		auditLog.setOperateTime(new Date());
		auditLog.setOperateUserId(u.getSwbUserId());
		auditLog.setOperateUserName(u.getUserName());
		auditLog.setOperateState(AuditLogBean.OPERATE_STATE_SUCCESS);
		auditLog.setOperateIp(IpUtil.getIpAddress(request));
		auditLog.setOperateUrl(request.getRequestURL().toString());
		if (conferenceService.publishConference(obj)) {
			if (obj.getPublishState() == 1) {
				auditLog.setOperateContent("发布会议成功! : "+obj.getConferenceID());
				auditLogService.addAuditLog(auditLog);
				return JsonUtil.success("发布会议成功!");
			}else {
				auditLog.setOperateContent("取消发布会议成功! : "+obj.getConferenceID());
				auditLogService.addAuditLog(auditLog);
				return JsonUtil.success("取消发布会议成功!");
			}
		} else {
			if (obj.getPublishState() == 1) {
				auditLog.setOperateContent("发布会议失败! : "+obj.getConferenceID());
				auditLogService.addAuditLog(auditLog);
				return JsonUtil.error("发布会议失败!");
			}else {
				auditLog.setOperateContent("取消发布会议失败! : "+obj.getConferenceID());
				auditLogService.addAuditLog(auditLog);
				return JsonUtil.error("取消发布会议失败!");
			}
		}
		
		
	}
	
	@GetMapping("/listGetConference")
	@ApiOperation(value = "获取已参加会议出席人列表", notes ="出席人列表查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchConferenceID", value = "会议id", paramType = "query")})
	public JsonQueryObject<ConferenceUser> getConferenceList(@ApiIgnore ConferenceUserQuery query,HttpServletRequest request,Model model){
		List<ConferenceUser> userList = conferenceUserService.getConferenceUserList(query);
		query.setResultList(userList);
		return new JsonQueryObject<>(query);
	}
	
	@GetMapping("/getConferenceUserIds")
	@ApiOperation(value = "获取已参加会议参加人ids", notes ="获取会议参加人ids")
	public JsonSuccessObject<List<String>> getConferenceUserIds(ConferenceUser obj,HttpServletRequest request){
		List<String> ids = conferenceUserService.getConferenceUserIds(obj);
		JsonSuccessObject<List<String>> returnResult = new JsonSuccessObject<List<String>>(ids);
		return returnResult;
	}
	
	@GetMapping("/getUserScope")
	@ApiOperation(value = "获取登录人code",notes = "获取登录人code")
	public JsonSuccessObject<String> getUserCode(HttpServletRequest request){
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.shyk,request);
		JsonSuccessObject<String> returnResult = new JsonSuccessObject<String>(u);
		return returnResult;
	}
	
	@PostMapping("/updateConferenceImg")
	@ApiOperation(value = "更新/新增会议图片", notes ="更新/新增会议图片")
	public JsonObject<Object> updateConferenceImg(Conference obj,HttpServletRequest request){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		obj.setLastModifiedDate(sdf.format(new Date()));
		try {
			conferenceService.updateConference(obj);
			//更新远程教育封面图
			Conference c=conferenceService.getConferenceById(obj.getConferenceID());
			if(c.getConferenceType().contains("5")) {
				Distancelearning d=new Distancelearning();
				d.setDistancelearningID(obj.getConferenceID());
				d.setDefaultImageId(obj.getDefaultImageId());
				distancelearningService.updateDistancelearning(d);
			}
			return JsonUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.error();
		}
	}
	
	@DeleteMapping("/deleteConferenceUser")
	@ApiOperation(value = "删除会议下参会人员", notes ="删除会议下参会人员")
	public JsonObject<Object> deleteConferenceUser(ConferenceUser obj,@ApiParam(value = "conferenceUserIDs", required = true) @RequestParam("ids") String[] ids){
		conferenceUserService.deleteConferenceUserByID(ids);
		Conference c = conferenceService.getConferenceById(obj.getConferenceID());
		c.setHeadNum(ids.length);
		conferenceService.updateNum(c);
		//更新远程教育的人员
		if(c.getConferenceType().contains("5")) {
			List<String> userIDs=conferenceUserService.getConferenceUserIds(obj);
			if(null!=userIDs && userIDs.size()>0) {
				Distancelearning d=new Distancelearning();
				d.setDistancelearningID(obj.getConferenceID());
				String[] userIds=userIDs.toArray(new String[userIDs.size()]);
				d.setUserIDs(userIds);
				distancelearningService.updateDistancelearning(d);
			}
		}
		
		return JsonSuccessObject.SUCCESS;
	}
	
	@GetMapping("/getConferenceById")
	@ApiOperation(value = "根据主键查询会议记录", notes ="工作日志详情")
	public JsonSuccessObject<Conference> getConferenceById(Conference obj,HttpServletRequest request,Model model){
		Conference conference = conferenceService.getConferenceById(obj.getConferenceID());
//		model.addAttribute("conference", conference);
		Conference c = new Conference();
		c.setConferenceType(conference.getConferenceType());
		JsonSuccessObject<Conference> returnResult = new JsonSuccessObject<>(c);
		return returnResult;
	}
	
	@GetMapping("/listGetConByIds")
	@ApiOperation(value = "根据主键查询会议记录", notes ="工作日志详情")
	public JsonSuccessObject<List<Conference>> getConferenceById(@ApiParam(value = "conferenceIDs", required = true) @RequestParam("ids") String[] ids){
		List<Conference> list = conferenceService.getConListByIds(ids);
		JsonSuccessObject<List<Conference>> returnResult = new JsonSuccessObject<>(list);
		return returnResult;
	}
	
	@DeleteMapping("/deleteConference")
	@ApiOperation(value = "删除会议", notes ="删除三会一课")
	public JsonObject<Object> deleteConference(@ApiParam(value = "conferenceIDs", required = true) @RequestParam("ids") String[] ids){
		if(null!=ids && ids.length>0) {
			for(String id:ids) {
				Distancelearning dis=distancelearningService.getDisByID(id);
				if(null!=dis) {
					dis.setActiveState(2);
					dis.setLastModifiedDate(new Date());
					distancelearningService.updateDisById(dis);
				}
			}
		}
		if (conferenceService.deleteConference(ids)) {
			return JsonUtil.success();
		}else {
			return JsonUtil.error();
		}
		
	}
	
	
	@GetMapping("/findPartyOrganizationLife")
	@ApiOperation(value = "支部组织生活统计平均数", notes ="获取支部组织生活统计平均数")
	public JsonSuccessObject<List<ConferenceStat>> findPartyOrganizationLife(ConferenceStatQuery query,HttpServletRequest request,Model model) throws Exception{
//		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
		if(query.getSearchScopeCode()==null||query.getSearchScopeCode()=="") {
			String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
			query.setSearchScopeCode(u);
		}
		if(query.getSearchScopeCode()==null||query.getSearchScopeCode()=="") {
			query.setSearchScopeCode("root");
		}
		if (query.getSearchYear()== null || "".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		List<ConferenceStat> partyOrganizationLifeList = conferenceStatService.findPartyOrganizationLife(query);
		List<ConferenceStat> list=new ArrayList<ConferenceStat>();
		for(int i=1;i<=4;i++) {
			ConferenceStat con=new ConferenceStat();
			boolean flag=true;
			for(ConferenceStat bean:partyOrganizationLifeList) {
				if(i==bean.getQuarter()) {
					BeanUtils.copyProperties(con,bean);
					flag=false;
					break;
				}
			}
			if(flag) {
				con.setDkAvgNum(0);
				con.setDxzAvgNum(0);
				con.setDzbwyhAvgNum(0);
				con.setZbdyAvgNum(0);
				
				con.setDkSunNum(0);
				con.setDxzSunNum(0);
				con.setDzbwyhSunNum(0);
				con.setZbdyNum(0);
				con.setQuarter(i);
			}
			list.add(con);
		}
		//本支部情况
		JsonSuccessObject<List<ConferenceStat>> returnResult = new JsonSuccessObject<>(list);
		return returnResult;
	}
	
	/**
	 * 获取其他类型的人员信息
	 * @date 2018年9月17日 上午11:32:26 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@PostMapping("/findNoClockingInTypeUserList")
	@ApiOperation(value = "获取已参加会议出席人列表", notes ="出席人列表查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchConferenceID", value = "会议id", paramType = "query")})
	public JsonQueryObject<ConferenceUser> findNoClockingInTypeUserList(@ApiIgnore ConferenceUserQuery query,HttpServletRequest request,Model model){
		List<ConferenceUser> userList = conferenceUserService.getConferenceUserList(query);
		query.setResultList(userList);
		return new JsonQueryObject<>(query);
	}
	
	
	//当创建会议类型包含远程教育时添加远程教育
	public void addOrUpdateDistancelearning(Conference conference,int type,HttpServletRequest request,HttpServletResponse response)throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Distancelearning obj=new Distancelearning ();
		if (PropertyUtil.objectNotEmpty(conference.getUserIDs())) {
			obj.setUserIDs(conference.getUserIDs());// 用户id
		}
		if (PropertyUtil.objectNotEmpty(conference.getConferenceID())) {
			obj.setDistancelearningID(conference.getConferenceID());
		}
		if (PropertyUtil.objectNotEmpty(conference.getConferenceBeginDate())) {
			obj.setBeginDate(conference.getConferenceBeginDate());// 开始时间
		}
		if (PropertyUtil.objectNotEmpty(conference.getConferenceEndDate())) {
			obj.setEndDate(conference.getConferenceEndDate());// 结束时间
		}
		if (PropertyUtil.objectNotEmpty(conference.getConferenceName())) {
			obj.setDistancelearningName(conference.getConferenceName());// 名称
		}
		if (PropertyUtil.objectNotEmpty(conference.getConferencePresentation())) {
			obj.setDistancelearningPresentation(conference.getConferencePresentation());// 简介
		}
		if (PropertyUtil.objectNotEmpty(conference.getIsSend())) {
			obj.setIsSend(conference.getIsSend());// 是否通知
		}
		if (PropertyUtil.objectNotEmpty(conference.getConferenceSite())) {
			obj.setDistancelearningSite(conference.getConferenceSite());// 会议地点
		}
		if (PropertyUtil.objectNotEmpty(conference.getCreateDate())) {
			obj.setCreateDate(sdf.parse(conference.getCreateDate()));// 创建时间
		}
		if (PropertyUtil.objectNotEmpty(conference.getPublishState())) {
			obj.setPublishState(conference.getPublishState());// 发布状态
		}
		if (PropertyUtil.objectNotEmpty(conference.getActiveState())) {
			obj.setActiveState(conference.getActiveState());
		}
		
		obj.setEditState(2);
		if(PropertyUtil.objectNotEmpty(conference.getDefaultImageId())) {
			obj.setDefaultImageId(conference.getDefaultImageId());//封面图
		}
		if(PropertyUtil.objectNotEmpty(conference.getCompere())) {
			obj.setCompere(conference.getCompere());//主持人	
		}
		if(PropertyUtil.objectNotEmpty(conference.getOrganizationId())) {
			obj.setOrganizationId(conference.getOrganizationId());//机构id
		}		
		obj.setDisType("ycjy");//类型
		if (PropertyUtil.objectNotEmpty(conference.getUserID())) {
			obj.setUserID(conference.getUserID());// 发布人id
		}
		if (PropertyUtil.objectNotEmpty(conference.getUserName())) {
			obj.setUserName(conference.getUserName());// 发布人姓名
		}
		if (PropertyUtil.objectNotEmpty(conference.getYear())) {
			obj.setYear(conference.getYear());
		}
		if (PropertyUtil.objectNotEmpty(conference.getQuarter())) {
			obj.setQuarter(conference.getQuarter());
		}
		//obj.setActiveState(DistancelearningQuery.ACTIVESTATE_YES);//默认启用
		if (obj.getPublishState() == null) {
			obj.setPublishState(DistancelearningQuery.PUBLISHSTATE_NO);//默认未发布
		}
		if (obj.getPublishState() != null && obj.getPublishState() == 1) {
			//发布时间
			obj.setPublishDate(new Date());
		}
		Distancelearning distancelearning=distancelearningService.getDisByID(obj.getDistancelearningID());
		if(PropertyUtil.objectNotEmpty(distancelearning)) {
			distancelearningService.updateDistancelearning(obj);	
		}else {
			//三会一课存在，远程教育不存在，查出所有人
			ConferenceUser conferenceUser=new ConferenceUser();
			conferenceUser.setConferenceID(conference.getConferenceID());
			List<String> userIds=conferenceUserService.getConferenceUserIds(conferenceUser);
			//合并为一个数组
			if(null!=userIds && userIds.size()>0) {
				List<String> list = new ArrayList<String>(Arrays.asList(obj.getUserIDs()));
				userIds.addAll(list);
				String[] ids = new String[userIds.size()];
				userIds.toArray(ids);
				obj.setUserIDs(ids);
			}
			//新增
			distancelearningService.addDistancelearning(obj);
			if (obj.getUserIDs() != null && obj.getUserIDs().length > 0) {
				distancelearningService.addDistancelearningUser(obj);
			}
			if (obj.getCourseIDs() != null && obj.getCourseIDs().length > 0) {
				distancelearningService.addDistancelearningCourse(obj);
			}
		}
	}
	
	
	
	
	@PutMapping("/updateWaitType")
	@ApiOperation(value = "更新党员考勤类型", notes ="更新党员考勤类型")
	public JsonObject<Object> updateWaitType(ConferenceBean obj,HttpServletRequest request,HttpServletResponse response){
		if (PropertyUtil.objectNotEmpty(obj.getSearchType()) && PropertyUtil.objectNotEmpty(obj.getUserIDs())) {
			if (conferenceUserService.updateWaitType(obj)) {
				return JsonUtil.success("更新成功!");
			}else {
				return JsonUtil.error("更新失败!");
			}
		}else {
			if (!PropertyUtil.objectNotEmpty(obj.getSearchType())) {
				return JsonUtil.error("修改考勤类型为空!请联系管理员");
			}else if(!PropertyUtil.objectNotEmpty(obj.getUserIDs())) {
				return JsonUtil.error("党员id为空!");
			}else {
				return JsonUtil.error("更新失败!");
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
}
